<?php
// +----------------------------------------------------------------------
// | OneThink [ WE CAN DO IT JUST THINK IT ]
// +----------------------------------------------------------------------
// | Copyright (c) 2013 http://www.onethink.cn All rights reserved.
// +----------------------------------------------------------------------
// | Author: huajie <banhuajie@163.com>
// +----------------------------------------------------------------------

namespace Common\Model;
use Think\Model;

/**
 * 文档基础模型
 */
class ArticleModel extends Model{

    /* 自动验证规则 */
    protected $_validate = array(
        array('name', '/^[a-zA-Z]\w{0,39}$/', '文档标识不合法', self::VALUE_VALIDATE, 'regex', self::MODEL_BOTH),
        array('name', '', '标识已经存在', self::VALUE_VALIDATE,'unique'),
        array('title', 'require', '标题不能为空', self::MUST_VALIDATE, 'regex', self::MODEL_BOTH),
        array('title', '1,80', '标题长度不能超过80个字符', self::MUST_VALIDATE, 'length', self::MODEL_BOTH),
        array('description', '1,140', '简介长度不能超过140个字符', self::VALUE_VALIDATE, 'length', self::MODEL_BOTH),
        array('cate_id', 'require', '分类不能为空', self::MUST_VALIDATE , 'regex', self::MODEL_INSERT),
        array('cate_id', 'require', '分类不能为空', self::EXISTS_VALIDATE , 'regex', self::MODEL_UPDATE),
        array('create_time', '/^\d{4,4}-\d{1,2}-\d{1,2}(\s\d{1,2}:\d{1,2}(:\d{1,2})?)?$/', '日期格式不合法,请使用"年-月-日 时:分"格式,全部为数字', self::VALUE_VALIDATE  , 'regex', self::MODEL_BOTH),
    );

    /* 自动完成规则 */
    protected $_auto = array(
        array('uid', 'is_login', self::MODEL_INSERT, 'function'),
        array('title', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
        array('content', 'base_encode', self::MODEL_BOTH, 'callback'),
        array('description', 'htmlspecialchars', self::MODEL_BOTH, 'function'),
        array('link_id', 'getLink', self::MODEL_BOTH, 'callback'),
        array('view', 0, self::MODEL_INSERT),
        array('comment', 0, self::MODEL_INSERT),
        array('create_time', 'getCreateTime', self::MODEL_BOTH,'callback'),
        array('update_time', NOW_TIME, self::MODEL_BOTH),
        array('status', '1', self::MODEL_INSERT),
    );

    protected function _after_find(&$result,$options) {
        $result['cover_id'] = get_cover($result['id']);
        $result['link_id'] = get_link($result['link_id']);
        $cate = M('Cate')->find($result['cate_id']);
        if($result['type'] == 2)
            $result['content'] = base64_decode($result['content']);
        $result['cate_title'] = $cate['title']? $cate['title'] :'';
        $result['cate_name'] = $cate['name']? $cate['name'] : '';
    }

    protected function _after_select(&$result,$options){
        $link_ids = array_column($result, 'link_id');
        $link_ids = array_unique($link_ids);
        $links = M('Url')->where(array('id'=>array('in',$link_ids)))->getField('id,url');
        $cover_ids= array_column($result, 'id');
        $cover_ids= array_unique($cover_ids);
        $users = M('user')->getField('id,name');
        $cates = M('Cate')->getField('id,title,name');
        $covers = M('Picture')->where(array('id'=>array('in',$cover_ids)))->getField('id,url,path');
        foreach ($result as $key => &$value) {
            if(isset($covers[$value['id']]['url']) || isset($covers[$value['id']]['path']))
                $value['cover_id'] = $covers[$value['id']]['url'] || $covers[$value['id']]['path'];
            $value['link_id'] = isset($links[$value['link_id']])? $links[$value['link_id']]: $value['link_id'];
            $value['author'] = $users[$value['uid']];
            if($value['type'] == 2)
                $value['content'] = base64_decode($value['content']);
            $value['cate_title'] = isset($cates[$value['cate_id']]['title'])? $cates[$value['cate_id']]['title']:'' ;
            $value['cate_name'] = isset($cates[$value['cate_id']]['name'])? $cates[$value['cate_id']]['name']:'';
        }
    }



    //对于单页模板钩子部分存压缩过的字符串
    protected function base_encode(){
        $content = I('post.content');
        return I('post.type') == '2'? base64_encode($content) : $content;
    }

    /**
     * 创建时间不写则取当前时间
     * @return int 时间戳
     * @author huajie <banhuajie@163.com>
     */
    protected function getCreateTime(){
        $create_time = I('post.create_time');
        return $create_time?strtotime($create_time):NOW_TIME;
    }

    /**
     * 获取链接id
     * @return int 链接对应的id
     * @author huajie <banhuajie@163.com>
     */
    protected function getLink(){
        $link = I('post.link_id');
        if(empty($link)){
            return 0;
        } else if(is_numeric($link)){
            return $link;
        }
        $res = D('Url')->update(array('url'=>$link));
        return $res['id'];
    }


    public function update($data = null){
        C('DEFAULT_FILTER', '');
        /* 获取数据对象 */
        if(null == $data)
            $data = $_POST;
        $data = $this->create($data);
        if(empty($data)){
            return false;
        }

        /* 添加或新增基础内容 */
        if(empty($data['id'])){ //新增数据
            $id = $this->add(); //添加基础内容
            if(!$id){
                $this->error = '新增失败！';
                return false;
            }
        } else { //更新数据
            $status = $this->save(); //更新基础内容
            if(false === $status){
                $this->error = '更新失败！';
                return false;
            }
        }

        //处理标签
        $tags = $data['tags'];
        $tags = explode(',', $tags);
        if($tags === FALSE){
            $tags = array();
        }

        if($data['id']){
            //更新时候先将原有标签统计减去1
            $orignal_tags = $this->getFieldById('tags', $data['id']);
            if($orignal_tags)
                M('Tags')->where(array('title'=>array('in', $orignal_tags)))->setDec('count');
        }

        foreach ($tags as $value) {
            if(M('Tags')->where("title = '{$value}'")->find())
                M('Tags')->where("title = '{$value}'")->setInc('count');
            else
                if($value)
                    M('Tags')->add(array('title'=>$value, 'count'=>1));
        }
        S('front_cache', NULL);
        return $data;
    }


    /**
     * 获取文档列表
     * @param  integer  $category 分类ID
     * @param  string   $order    排序规则
     * @param  integer  $status   状态
     * @param  boolean  $count    是否返回总数
     * @param  string   $field    字段 true-所有字段
     * @return array              文档列表
     */
    public function lists($category, $order = '`id` DESC', $status = 1, $field = true, $limit = NULL){
        $map = $this->listMap($category, $status);
        is_numeric($limit) && $this->limit($limit);
        return $this->field($field)->where($map)->order($order)->select();
    }

    /**
     * 设置where查询条件
     * @param  number  $category 分类ID
     * @param  number  $type      单页还是内容
     * @param  integer $status   状态
     * @return array             查询条件
     */
    private function listMap($category, $status = 1, $type = 1){
        /* 设置状态 */
        $map = array('status' => $status);
        $map['type'] = $type;
        /* 设置分类 */
        if(!is_null($category)){
            if(is_numeric($category)){
                $map['cate_id'] = $category;
            } else {
                $map['cate_id'] = array('in', str2arr($category));
            }
        }

        $map['create_time'] = array('lt', NOW_TIME);
        if(I('get.year') && I('get.month')){
            $month = I('get.month');
            $year = I('get.year');
            $begin_time = strtotime($year . $month . "01");
            $end_time = strtotime("+1 month", $begin_time);
            $map['create_time'] = array(array('gt', $begin_time),array('lt', $end_time));
        }
        if(I('get.kw')){
            $kw = trim(I('get.kw'));
            $map['title'] = array('like',"%{$kw}%");
            $like_id = $this->where("content like '%{$kw}%'")->getField('id', true);
            if($like_id)
                $map['id'] = array('in', $like_id);
        }
        $tags = trim(I('get.tag'));
        if($tags){
            $map = array('tags'=>array('like', "%{$tags}%"));
        }
        $map['_string'] = 'deadline = 0 OR deadline > ' . NOW_TIME;

        return $map;
    }

}
